

/*
 * 适配横竖屏
 *
 *
 * 程序猿:
 *   Geek7
 * 最后修改日期:
 *    2020/06/09
 */



import Watcher from "./Watcher";

const { ccclass, property } = cc._decorator;

export enum EOrientation {
    /**
     * 横屏
     */
    LANDSCAPE = 0,

    /**
     * 竖屏
     */
    PORTRAIT = 1
}

@ccclass
export default class ViewOrientation extends cc.Component {

    /** 当屏幕发生翻转时 或者 大小发生变化时 */
    static readonly ON_VIEW_RESIZE = 'ON_VIEW_RESIZE';

    private canvas: cc.Canvas = null;
    private canvasframe = {
        min: 0,
        max: 0
    }
    start() {
        this.canvas = cc.Canvas.instance;
        let canvasSize = this.canvas.designResolution;
        this.canvasframe.min = Math.min(canvasSize.width, canvasSize.height);
        this.canvasframe.max = Math.max(canvasSize.width, canvasSize.height);
        let oldOrientation = canvasSize.width > canvasSize.height ? EOrientation.LANDSCAPE : EOrientation.PORTRAIT;
        let resizeFunc = () => {
            let curOrientation = window.innerWidth > window.innerHeight ? EOrientation.LANDSCAPE : EOrientation.PORTRAIT;
            this.canvas.fitHeight = curOrientation == EOrientation.PORTRAIT;
            this.canvas.fitWidth = !this.canvas.fitHeight;
            this.canvas.designResolution = cc.size(this.canvas.fitHeight ? this.canvasframe.min : this.canvasframe.max, this.canvas.fitWidth ? this.canvasframe.min : this.canvasframe.max);
            oldOrientation = curOrientation;
            Watcher.dispatch(ViewOrientation.ON_VIEW_RESIZE, {
                dir: curOrientation,
                size: this.canvas.designResolution
            });
        }
        cc.view.setResizeCallback(resizeFunc);
        resizeFunc();
    }
}
